/*
 * Copyright (c) 2006, 2007 Sun Microsystems, Inc.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package org.sunspotworld.demo;

import java.io.IOException;

import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

import org.sunspotworld.robowulf.Robowulf;

import com.sun.spot.peripheral.IDriver;
import com.sun.spot.peripheral.Spot;
import com.sun.spot.resourcesharing.ResourceUnavailableException;
import com.sun.spot.sensorboard.EDemoBoard;
import com.sun.spot.sensorboard.peripheral.ITriColorLED;
import com.sun.spot.sensorboard.peripheral.LEDColor;
import com.sun.spot.util.BootloaderListener;
import com.sun.spot.util.Utils;
import org.sunspotworld.robowulf.Robowulf;
import org.sunspotworld.robowulf.irsensor.IRSensor;
import org.sunspotworld.util.Units;

/**
 * The startApp method of this class is called by the VM to start the
 * application.
 *
 * The manifest specifies this class as MIDlet-1, which means it will
 * be selected for execution.
 */
public class SunSpotApplication extends MIDlet implements IDriver {

    private ITriColorLED [] leds = EDemoBoard.getInstance().getLEDs();
    
    protected void startApp() throws MIDletStateChangeException {
        System.out.println("Hello, world");
        try {
            Spot.getInstance().getOTACommandServer().setSuspended(false);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        new BootloaderListener().start();   // monitor the USB (if connected) and recognize commands from host


//                IRSensor s1 = new IRSensor("left", EDemoBoard.getInstance().getScalarInputs()[2]);
//                IRSensor s2 = new IRSensor("right", EDemoBoard.getInstance().getScalarInputs()[3]);
//
//                try {
//                while (true) {
//                    System.out.println("L" + s1.getRawValue());
//                    System.out.println("R" + s2.getRawValue());
//                    Utils.sleep(10);
//                }
//                } catch (ResourceUnavailableException e) {
//                    e.printStackTrace();
//                }


        Robowulf.getInstance().stop();

        Robowulf.getInstance().setUnits(Units.INCHES);
        
        Spot.getInstance().getDriverRegistry().add(this);
        
        while (true) {
            blinkLEDs(LEDColor.GREEN, 250, 10);

            EDemoBoard.getInstance().getSwitches()[0].waitForChange();

            Robowulf.getInstance().forward(60F);
            if(0==0)continue;

        	for (int i = 0; i < 6; i++) {
        		//Robowulf.getInstance().forward(12F); //Robowulf.getInstance().forward(10.61F); // 1 rev
        		Robowulf.getInstance().forward(12F);
        		Robowulf.getInstance().left(60F);
        	}
        	
        	Robowulf.getInstance().left(360F);
        	Robowulf.getInstance().right(360F);
        	
        	Robowulf.getInstance().forward(12F);
        	Robowulf.getInstance().left(180F);
        	Robowulf.getInstance().forward(24F);
        	Robowulf.getInstance().left(180F);
        	Robowulf.getInstance().forward(12F);
        	
        	Robowulf.getInstance().right(1080F);
            //Robowulf.getInstance().forward(120F);
        }

        /*
        Robowulf.getInstance().setUnits(Robowulf.INCHES);
        for (int i = 0; i< 5; i++) {
            Robowulf.getInstance().forward(24);
            Robowulf.getInstance().backward(24);
            Robowulf.getInstance().left(180);
            Robowulf.getInstance().right(180);
            Robowulf.getInstance().stop();
        }
        try {
            Robowulf.getInstance().senseFrom(Robowulf.FORWARD_ULTRASOUND_SENSOR);
            blinkLEDs(LEDColor.GREEN, 250, 10);
        } catch (ResourceUnavailableException ex) {
            blinkLEDs(LEDColor.RED, 250, 10);
            ex.printStackTrace();
        }//*/
    }
    
    private void blinkLEDs(LEDColor color, long time, int repeat) {
        for (int i=0; i<repeat; i++) {
            for (int j=0; j<leds.length; j++) {
                leds[j].setColor(color);
                leds[j].setOn();
            }
            Utils.sleep(time);
            for (int j=0; j<leds.length; j++) {
                leds[j].setOff();
            }
            Utils.sleep(time);
        }
    }
    
    protected void pauseApp() {
        // This is not currently called by the Squawk VM
    }
    
    /**
     * Called if the MIDlet is terminated by the system.
     * I.e. if startApp throws any exception other than MIDletStateChangeException,
     * if the isolate running the MIDlet is killed with Isolate.exit(), or
     * if VM.stopVM() is called.
     * 
     * It is not called if MIDlet.notifyDestroyed() was called.
     *
     * @param unconditional If true when this method is called, the MIDlet must
     *    cleanup and release all resources. If false the MIDlet may throw
     *    MIDletStateChangeException  to indicate it does not want to be destroyed
     *    at this time.
     */
    protected void destroyApp(boolean unconditional) throws MIDletStateChangeException {
        for (int i = 0; i < 8; i++) {
            leds[i].setOff();
        }
    }

	public String getDriverName() {	return "Oh hai"; }

	public void setUp() {}

	public void shutDown() {}
	public boolean tearDown() {	return false; }
}
